package hot100;

import java.util.Arrays;
import java.util.Comparator;

public class merge2 {
    public int[][] merge(int[][] intervals) {
        //排序，重写比较器
        Arrays.sort(intervals,new Comparator<int[]>() {
            public int compare(int[] o1,int[] o2) {
                return o1[0] - o2[0];
            }
        });
        //设置指针
        int[] pre = intervals[0];
        //k，原地记录 节约空间
        int k = 0;
        for(int i = 1;i < intervals.length;i++) {
            int[] cur = intervals[i];
            if(pre[1] >= cur[0]) {
                //同一个区间，合并
                int tem = Math.max(pre[1],cur[1]);
                pre = new int[] {pre[0],tem};
            }else {
                intervals[k] = pre;
                k++;
                pre = cur;
            }
        }
        //添加最后一个区间
        intervals[k++] = pre;
        return Arrays.copyOfRange(intervals,0,k);
    }
}
